package com.ddd.mill.infrastructure.utils;

import com.ddd.mill.infrastructure.redis.utils.RedisUtil;
import org.springframework.util.Assert;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户会话工具类
 */
public final class UserTokenUtil {
    // 加密密匙 (长度必须32位)
    private static final String token_secret_key = "qwqw1234qwqw1234";
    public static final long expire_time = 30 * 24 * 3600;
    private static RedisUtil sRedisUtil;
    @Resource
    private RedisUtil redisUtil;

    @PostConstruct
    public void initialize() {
        sRedisUtil = this.redisUtil;
    }

    public static String generateUserToken(Long userId) {
        return generateUserTokenReal(userId, 1);
    }

    public static String generateUserToken(Long userId, Long userProfileId) {
        Map<String, Object> userSession = new HashMap<>();
        userSession.put("userProfileId", userProfileId);
        return generateUserTokenReal(userId, userSession);
    }

    private static String generateUserTokenReal(Long userId, Object o) {
        long currentTime = System.currentTimeMillis() / 1000;
        StringBuilder builder = new StringBuilder();
        builder.append("new&").append(ServletUtils.getAppId()).append("&").append(userId).append("&").append(currentTime);
        String userToken = AESUtil.encrypt(builder.toString(), token_secret_key);
        Assert.isTrue(sRedisUtil.set(userToken, o, expire_time), "token生成失败");
        return userToken;
    }

    public static Long fetchUserId(String userToken) {
        if (userToken == null) {
            return null;
        }
        String content = AESUtil.decrpyt(userToken, token_secret_key).trim();
        if (content == null) {
            return null;
        }
        String[] data = content.split("&");
        if (data.length != 3) {
            return null;
        }
        Long currentTime = Long.valueOf(data[1]);
        Long expireTime = Long.valueOf(data[2]) + currentTime;
        if (System.currentTimeMillis() / 1000 > expireTime) {
            // 当前userToken已经过期了
            return null;
        }
        return Long.valueOf(data[0]);
    }

    public static String[] parseUserToken(String userToken) {
        if (userToken == null) {
            return null;
        }
        String content = AESUtil.decrpyt(userToken, token_secret_key).trim();
        if (content == null) {
            return null;
        }
        String[] data = content.split("&");
        if (data.length != 4) {
            return null;
        }
        if(!sRedisUtil.hasKey(userToken)) {
            return null;
        }
        return data;
    }
}
